﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MyUtility;
using MyAuction;
using MyUtility.UploadFile;

namespace MyAdmin.Admin
{
    public partial class Ad_SMSSession_Edit : System.Web.UI.Page
    {
        public GetRole mGetRole;
        SMSSession mSession = new SMSSession();

        string EditID = string.Empty;

        public string ParentPath = "../Admin/Ad_SMSSession.aspx";

        private void BindCombo(int type)
        {
            try
            {
                Category mCate = new Category();

                switch (type)
                {
                    case 1:
                        sel_Status.DataSource = MyUtility.MyEnum.CrateDatasourceFromEnum(typeof(SMSSession.Status));
                        sel_Status.DataTextField = "Text";
                        sel_Status.DataValueField = "ID";
                        sel_Status.DataBind();
                        break;
                    case 2:
                        sel_SessionType.DataSource = MyUtility.MyEnum.CrateDatasourceFromEnum(typeof(SMSSession.SessionType));
                        sel_SessionType.DataTextField = "Text";
                        sel_SessionType.DataValueField = "ID";
                        sel_SessionType.DataBind();
                        break;
                    case 3: // Bind dữ liệu về giờ
                        sel_StartHour.DataSource = sel_StopHour.DataSource = MyEnum.GetDataFromTime(3, string.Empty,string.Empty);
                        sel_StartHour.DataValueField = sel_StopHour.DataValueField = "ID";
                        sel_StartHour.DataTextField = sel_StopHour.DataTextField = "Text";
                        sel_StartHour.DataBind();
                        sel_StopHour.DataBind();
                        sel_StartHour.Items.Insert(0, new ListItem("--Giờ--", "-1"));
                        sel_StopHour.Items.Insert(0, new ListItem("--Giờ--", "-1"));
                        break;
                    case 4: // Bind dữ liệu về Phút
                        sel_StartMinute.DataSource = sel_StopMinute.DataSource = MyEnum.GetDataFromTime(4, string.Empty, string.Empty);
                        sel_StartMinute.DataValueField = sel_StopMinute.DataValueField = "ID";
                        sel_StartMinute.DataTextField = sel_StopMinute.DataTextField = "Text";
                        sel_StartMinute.DataBind();
                        sel_StopMinute.DataBind();
                        sel_StartMinute.Items.Insert(0, new ListItem("--Phút--", "0"));
                        sel_StopMinute.Items.Insert(0, new ListItem("--Phút--", "0"));
                        break;
                    case 5: // Bind dữ liệu về Giây
                        sel_StartSecond.DataSource = sel_StopSecond.DataSource = MyEnum.GetDataFromTime(5, string.Empty, string.Empty);
                        sel_StartSecond.DataValueField = sel_StopSecond.DataValueField = "ID";
                        sel_StartSecond.DataTextField = sel_StopSecond.DataTextField = "Text";
                        sel_StartSecond.DataBind();
                        sel_StopSecond.DataBind();
                        sel_StartSecond.Items.Insert(0, new ListItem("--Giây--", "0"));
                        sel_StopSecond.Items.Insert(0, new ListItem("--Giây--", "0"));
                        break;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private bool CheckPermission()
        {
            try
            {
                if (mGetRole.ViewRole == false)
                {
                    Response.Redirect(mGetRole.URLNotView, false);
                    return false;
                }
                if (!string.IsNullOrEmpty(EditID))
                {
                    lbtn_Save.Visible = lbtn_Accept.Visible = mGetRole.EditRole;
                    link_Add.Visible = mGetRole.AddRole;
                }
                else
                {
                    lbtn_Save.Visible = lbtn_Accept.Visible = link_Add.Visible = mGetRole.AddRole;
                }
                sel_Status.Disabled = !mGetRole.PublishRole || !mGetRole.UnPublishRole;

            }
            catch (Exception ex)
            {
                MyLogfile.WriteLogError(ex, true, MyNotice.AdminError.CheckPermissionError, "Chilinh");
                return false;
            }
            return true;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //Phân quyền
                if (ViewState["Role"] == null)
                {
                    mGetRole = new GetRole(LocalConfig.ListPage.SMSSession, Member.MemberGroupID());
                }
                else
                {
                    mGetRole = (GetRole)ViewState["Role"];
                }

                //Lấy ID nếu là trước hợp Sửa
                EditID = Request.QueryString["ID"] == null ? string.Empty : Request.QueryString["ID"];

                if (!CheckPermission())
                    return;

                MyAdmin.MasterPages.Admin mMaster = (MyAdmin.MasterPages.Admin)Page.Master;
                mMaster.str_PageTitle = MyEnum.StringValueOf(LocalConfig.ListPage.SMSSession);
                mMaster.str_TitleSearchBox = "Thông tin về "+ MyEnum.StringValueOf(LocalConfig.ListPage.SMSSession);

                if (!IsPostBack)
                {
                    BindCombo(1);
                    BindCombo(2);
                    BindCombo(3);
                    BindCombo(4);
                    BindCombo(5);

                    //Nếu là Edit
                    if (!string.IsNullOrEmpty(EditID))
                    {
                        DataTable mTable = mSession.Select(1, EditID.ToString());

                        //Lưu lại thông tin OldData để lưu vào MemberLog
                        ViewState["OldData"] = MyXML.GetXML(mTable);

                        if (mTable != null && mTable.Rows.Count > 0)
                        {

                            #region MyRegion
                            DataRow mRow = mTable.Rows[0];
                            tbx_SessionID.Value = mRow["SessionID"].ToString();
                            tbx_SessionName.Value = mRow["SessionName"].ToString();

                            tbx_OriginalPrice.Value = mRow["OriginalPrice"].ToString();
                            tbx_BuyNowPrice.Value = mRow["BuyNowPrice"].ToString();
                            tbx_SMSCode.Value = mRow["SMSCode"].ToString();
                            tbx_ServiceID.Value = mRow["ServiceID"].ToString();

                            tbx_StepPrice.Value = mRow["StepPrice"].ToString();
                            tbx_Cost.Value = mRow["Cost"].ToString();
                            tbx_DistanceTime.Value = mRow["DistanceTime"].ToString();
                            tbx_Priority.Value = mRow["Priority"].ToString();

                            sel_SessionType.SelectedIndex = sel_SessionType.Items.IndexOf(sel_SessionType.Items.FindByValue(mRow["SessionTypeID"].ToString()));
                            sel_Status.SelectedIndex = sel_Status.Items.IndexOf(sel_Status.Items.FindByValue(mRow["StatusID"].ToString()));

                            if (mRow["StartDate"] != DBNull.Value)
                            {
                                DateTime mDateTime = (DateTime)mRow["StartDate"];
                                tbx_StartDate.Value = mDateTime.ToString(MyConfig.ShortDateFormat);
                                sel_StartHour.SelectedIndex = sel_StartHour.Items.IndexOf(sel_StartHour.Items.FindByValue(mDateTime.Hour.ToString()));
                                sel_StartMinute.SelectedIndex = sel_StartMinute.Items.IndexOf(sel_StartMinute.Items.FindByValue(mDateTime.Minute.ToString()));
                                sel_StartSecond.SelectedIndex = sel_StartSecond.Items.IndexOf(sel_StartSecond.Items.FindByValue(mDateTime.Second.ToString()));
                            }

                            if (mRow["StopDate"] != DBNull.Value)
                            {
                                DateTime mDateTime = (DateTime)mRow["StopDate"];
                                tbx_StopDate.Value = mDateTime.ToString(MyConfig.ShortDateFormat);
                                sel_StopHour.SelectedIndex = sel_StopHour.Items.IndexOf(sel_StopHour.Items.FindByValue(mDateTime.Hour.ToString()));
                                sel_StopMinute.SelectedIndex = sel_StopSecond.Items.IndexOf(sel_StopSecond.Items.FindByValue(mDateTime.Minute.ToString()));
                                sel_StopSecond.SelectedIndex = sel_StopSecond.Items.IndexOf(sel_StartSecond.Items.FindByValue(mDateTime.Second.ToString()));
                            }

                            #endregion
                        }
                    }
                    else
                    {
                        tbx_SessionID.Value = mSession.CreateSessionID();
                    }
                }
            }
            catch (Exception ex)
            {
                MyLogfile.WriteLogError(ex, true, MyNotice.AdminError.LoadDataError, "Chilinh");
            }

        }
        
        private void AddNewRow(ref DataSet mSet)
        {
            MyConvert.ConvertDateColumnToStringColumn(ref mSet);
            DataRow mNewRow = mSet.Tables["Child"].NewRow();

            if (!string.IsNullOrEmpty(EditID))
                mNewRow["SessionID"] = EditID;
            else
                mNewRow["SessionID"] = tbx_SessionID.Value;

            if (sel_SessionType.SelectedIndex >= 0 && sel_SessionType.Items.Count > 0)
            {
                mNewRow["SessionTypeID"] = int.Parse(sel_SessionType.Value);
                mNewRow["SessionTypeName"] = sel_SessionType.Items[sel_SessionType.SelectedIndex].Text;
            }
                       
            mNewRow["SessionName"] = tbx_SessionName.Value;
            mNewRow["SMSCode"] = tbx_SMSCode.Value;
            mNewRow["ServiceID"] = tbx_ServiceID.Value;
            mNewRow["CreateDate"] = DateTime.Now.ToString(MyConfig.DateFormat_InsertToDB);

            int Priority = 0,DistanceTime =0;
            float OriginalPrice = 0, BuyNowPrice = 0, StepPrice = 0, Cost = 0;

            #region MyRegion
            if (int.TryParse(tbx_Priority.Value, out Priority))
            {
                mNewRow["Priority"] = Priority;
            }
            if (int.TryParse(tbx_DistanceTime.Value, out DistanceTime))
            {
                mNewRow["DistanceTime"] = DistanceTime;
            }
            if (float.TryParse(tbx_OriginalPrice.Value, out OriginalPrice))
            {
                mNewRow["OriginalPrice"] = OriginalPrice;
            }
            if (float.TryParse(tbx_BuyNowPrice.Value, out BuyNowPrice))
            {
                mNewRow["BuyNowPrice"] = BuyNowPrice;
            }
            if (float.TryParse(tbx_StepPrice.Value, out StepPrice))
            {
                mNewRow["StepPrice"] = StepPrice;
            }
            if (float.TryParse(tbx_Cost.Value, out Cost))
            {
                mNewRow["Cost"] = Cost;
            } 
            #endregion

            if (sel_Status.SelectedIndex >= 0 && sel_Status.Items.Count > 0)
            {
                mNewRow["StatusID"] = int.Parse(sel_Status.Value);
                mNewRow["StatusName"] = sel_Status.Items[sel_Status.SelectedIndex].Text;
            }

            if (tbx_StartDate.Value.Length > 0)
            {
                int Hour = 0;
                int Minute = 0;
                int Second = 0;
                DateTime TempDate = DateTime.ParseExact(tbx_StartDate.Value, "dd/MM/yyyy", null);

                if (sel_StartHour.SelectedIndex > 0)
                    int.TryParse(sel_StartHour.Value, out Hour);
                if (sel_StartMinute.SelectedIndex > 0)
                    int.TryParse(sel_StartMinute.Value, out Minute);
                if (sel_StartSecond.SelectedIndex > 0)
                    int.TryParse(sel_StartSecond.Value, out Second);

                mNewRow["StartDate"] = new DateTime(TempDate.Year, TempDate.Month, TempDate.Day, Hour, Minute, Second).ToString(MyConfig.DateFormat_InsertToDB);
            }

            if (tbx_StopDate.Value.Length > 0)
            {
                int Hour = 0;
                int Minute = 0;
                int Second = 0;
                DateTime TempDate = DateTime.ParseExact(tbx_StopDate.Value, "dd/MM/yyyy", null);

                if (sel_StopHour.SelectedIndex > 0)
                    int.TryParse(sel_StopHour.Value, out Hour);
                if (sel_StopMinute.SelectedIndex > 0)
                    int.TryParse(sel_StopMinute.Value, out Minute);
                if (sel_StopSecond.SelectedIndex > 0)
                    int.TryParse(sel_StopSecond.Value, out Second);

                mNewRow["StopDate"] = new DateTime(TempDate.Year, TempDate.Month, TempDate.Day, Hour, Minute, Second).ToString(MyConfig.DateFormat_InsertToDB);
            }

            mNewRow["SearchName"] = tbx_SessionName.Value + ", " + MyText.RemoveSignVietnameseString(tbx_SessionName.Value) + ", " + MyText.RemoveSignVietnameseString(tbx_SessionName.Value).Replace(" ", "");

            mNewRow["SearchContent"] = mNewRow["SearchName"] + ", " + MyConvert.ConvertDataToSearchText(mNewRow, new string[] { "SessionID", "OriginalPrice", "BuyNowPrice", "SMSCode", "ServiceID", "StepPrice", "Cost", "DistanceTime", "Priority" });

            mSet.Tables["Child"].Rows.Add(mNewRow);
            mSet.AcceptChanges();
        }

        private void Save(bool IsApply)
        {
            try
            {
                DataSet mSet = mSession.CreateDataSet();
                AddNewRow(ref mSet);
                //Nếu là Edit
                if (!string.IsNullOrEmpty(EditID))
                {
                    if (mSession.Update(0, mSet.GetXml()))
                    {
                        #region Log member
                        MemberLog mLog = new MemberLog();
                        MemberLog.ActionType Action = MemberLog.ActionType.Update;
                        mLog.Insert("SMSSession", ViewState["OldData"].ToString(), mSet.GetXml(), Action, true, string.Empty);
                        #endregion

                        if (IsApply)
                            MyMessage.ShowMessage("Cập nhật dữ liệu thành công.");
                        else
                        {
                            Response.Redirect(ParentPath, false);
                        }
                    }
                    else
                    {
                        MyMessage.ShowMessage("Cập nhật dữ liệu (KHÔNG) thành công!");
                    }
                }
                else
                {
                    if (mSession.Insert(0, mSet.GetXml()))
                    {
                        #region Log member
                        MemberLog mLog = new MemberLog();
                        MemberLog.ActionType Action = MemberLog.ActionType.Insert;
                        mLog.Insert("SMSSession", string.Empty, mSet.GetXml(), Action, true, string.Empty);
                        #endregion

                        if (IsApply)
                            MyMessage.ShowMessage("Cập nhật dữ liệu thành công.");
                        else
                        {
                            Response.Redirect(ParentPath, false);
                        }
                    }
                    else
                    {
                        MyMessage.ShowMessage("Cập nhật dữ liệu (KHÔNG) thành công!");
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void lbtn_Save_Click(object sender, EventArgs e)
        {
            try
            {
                Save(false);
            }
            catch (Exception ex)
            {
                MyLogfile.WriteLogError(ex, true, MyNotice.AdminError.SaveDataError, "Chilinh");
            }
        }

        protected void lbtn_Apply_Click(object sender, EventArgs e)
        {
            try
            {
                Save(true);
            }
            catch (Exception ex)
            {
                MyLogfile.WriteLogError(ex, true, MyNotice.AdminError.SaveDataError, "Chilinh");
            }
        }
    }
}
